<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >结算单管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}结算单</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        ref="pageForm"
      >
        <el-form-item label="结算单号：">{{pageData.billId}}</el-form-item>
        <el-form-item label="结算单周期：">{{pageData.startDate+'-'+pageData.endDate}}</el-form-item>
        <el-form-item label="我方主体：">{{pageData.ourMain}}</el-form-item>
        <el-form-item label="客户名称：">{{pageData.customerName}}</el-form-item>
        <el-form-item label="客户全称：">{{pageData.customerFullName}}</el-form-item>
        <el-form-item label="结算方式：">{{mapOptionLabel(SETTLEWAY,pageData.settleWay)}}</el-form-item>
        <el-form-item label="实际总结算金额(元)：">{{pageData.settlementAmount}}</el-form-item>
        <el-form-item label="核减金额(元)：" v-if="pageData.settleWay == 1">{{pageData.subtractAmount}}</el-form-item>
        <el-form-item label="结算单生成人：">{{pageData.createby}}</el-form-item>
        <el-form-item label="结算单生成时间：">{{pageData.createTime}}</el-form-item>
        <el-form-item label="发票状态：">{{mapOptionLabel(INVOICESTATEDATA,pageData.invoiceStatus)}}</el-form-item>
      </el-form>
      <el-table
        border
        stripe
        height="500"
        :data="tableData"
      >
       
        <el-table-column
          align="center"
          v-for="(item, index) in tableColumn"
          :label="item.label"
          :key="index"
          
        >
          <el-table-column
            :resizable="false"
            align="center"
            :label="item.prop === 'reportTime' ? '总计' : getTableDataSumValue(item.prop, {rate: ['rebates']})"
            :prop="item.prop"
            class-name="u-table--total"
            :width="item.prop === 'reportTime' && 110"
          >
          <template slot-scope="scope">
            <!-- 账号名称 -->
            <template v-if="item.prop === 'accountName'">{{scope.row.accountName == '' || scope.row.accountName == null ? '-' : scope.row.accountName}}</template>
            <!-- 服务费率 -->
            <template v-else-if="item.prop === 'serviceRate'">{{scope.row.serviceRate + '%'}}</template>
            <!-- 当前返点 -->
            <template v-else-if="item.prop === 'rebates'">{{scope.row.rebates + '%'}}</template>
            <!-- 其他 -->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="$router.back()"
        >返回</el-button>
        <el-button
          size="small"
          type="primary"
          v-if="['create', 'edit'].includes(pageAction)"
          @click="handleEnsure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";

import { mapOptionLabel,decimalMultiply } from "@/util";
import { MYACCOUNT,SETTLEWAY, INVOICESTATEDATA } from "@/assets/js/flow-option";
export default {
  components: {
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      MYACCOUNT,
      SETTLEWAY,
      INVOICESTATEDATA,
      pageAction: this.$route.query.action,

      // 下拉
      customerIntroductOptions:[],
      customerAccountOptions:[],
      pageData: {
        accountDataList:{
          list:[]
        }
      },
      tableData:[],
      tableColumn: [
        {
          label: "日期（天）",
          prop: "reportTime",
          visible: true
        },
        {
          label: "客户名称",
          prop: "customerName",
          visible: true
        },
        {
          label: "产品名称",
          prop: "productName",
          visible: true
        },
        {
          label: "平台名称",
          prop: "platformName",
          visible: true
        },
        {
          label: "登陆账号",
          prop: "username",
          visible: true
        },
        {
          label: "账号名称",
          prop: "accountName",
          visible: true
        },
        {
          label: "账号ID",
          prop: "usernameId",
          visible: true
        },
        {
          label: "当日返点",
          prop: "rebates",
          visible: true
        },
        {
          label: "当日消耗（元）",
          prop: "consum",
          visible: true
        },
        {
          label: "激励消耗（元）",
          prop: "incentiveConsum",
          visible: true
        },
        {
          label: "折后消耗（元）",
          prop: "afterDiscountConsum",
          visible: true
        },
        {
          label: "服务费率",
          prop: "serviceRate",
          visible: true
        },
        {
          label: "商务负责人",
          prop: "business",
          visible: true
        }
      ],
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    mapOptionLabel,
    decimalMultiply,
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    // 下拉
    fetchcustomerIntroductOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerIntroductOptions = res.data.data;
        }
      });
    },
    fetchcustomerAccountOptions(id) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer_check/get_customer",
        params: {
          customerId: id
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerAccountOptions = res.data.data;
        }
      });
    },
    handleCustomerIntroduct(id){
      this.ruleForm.customerAccount = null
      this.fetchcustomerAccountOptions(id)
    },
    // 确定
    handleEnsure() {
      // if (this.pageAction === "edit") {
      //   this.updateDetail();
      // } else {
      //   this.createDetail();
      // }
    },
    // 详情
    getDetail() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/statements/get_by_bill_id",
        params: {
          billId: this.$route.query.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.pageData = res.data.data;

          this.tableData = this.modTableDataSumList(
            res.data.data.accountDataList.sumList,
            res.data.data.accountDataList.list
          );
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return value
        }
        return String(value);
      }
      return "";
    },
  },
  
  created() {
   this.fetchcustomerIntroductOptions();
    if (["edit", "detail"].includes(this.pageAction)) {
      this.getDetail();
    }
  }
};
</script>